import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:like_button/like_button.dart';
import 'package:live_music/components/feedback/PageFeedBack.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/event/commentEvent.dart';
import 'package:live_music/models/comment_detail_model.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/pages/comment/comment_detail.dart';
import 'package:live_music/services/commentService.dart';
import 'package:live_music/services/momentService.dart';
import 'package:live_music/services/operationServiece.dart';
import 'package:live_music/services/userService.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/commentParse.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/screen_utils.dart';
import 'package:live_music/utils/sp_utils.dart';
import 'package:live_music/utils/util.dart';

class MomentCommentDetail extends StatefulWidget {
  MomentCommentDetail({Key key, this.momentDetailData}) : super(key: key);
  MomentDetailModel momentDetailData;
  @override
  _MomentCommentDetailState createState() => _MomentCommentDetailState();
}

class _MomentCommentDetailState extends State<MomentCommentDetail>
    with SingleTickerProviderStateMixin {
  EasyRefreshController _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  // 列表数组模型
  List<CommentDetailModel> _commentListModel;
  int pageNo = 1;
  int pageSize = 20;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg;
  List options = ['删除'];
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();

    EventBusUtils.getInstance().on<AfterPublishComment>().listen((event) {
      if (event.parentId != 0) {
        for (int i = 0; i < _commentListModel.length; i++) {
          if (_commentListModel[i].id == event.parentId) {
            print(_commentListModel[i].id);
            if (_commentListModel[i].replyCount == null) {
              _commentListModel[i].replyCount = 1;
            } else {
              _commentListModel[i].replyCount++;
            }
          }
        }
        setState(() {
          _commentListModel = _commentListModel;
        });
      } else {
        setState(() {
          _commentListModel.insert(0, event.newComment);
        });
      }
    });
    getData();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  getData({bool replace = true}) async {
    try {
      Map<String, dynamic> data = {
        "pageNo": pageNo,
        "pageSize": pageSize,
        "momentId": widget.momentDetailData.id,
        "parentId": 0
      };
      Map<String, dynamic> result =
          await CommentService.queryMomentComment(data);
      List<dynamic> momentList = result['body'];
      CommentListModel momentListModel = CommentListModel.fromJson(momentList);
      setState(() {
        pageNo++;
        hasMore = pageSize == momentListModel.list.length;
        if (replace) {
          _commentListModel = momentListModel.list;
        } else {
          _commentListModel.addAll(momentListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    setState(() {
      pageNo = 1;
    });
    await getData(replace: true);
    if (error) {
      setState(() => error = false);
    }
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await getData(replace: false);
    }
    // // 结束加载
    // _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
    await Future.delayed(const Duration(seconds: 0), () {
      _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: MediaQuery.of(context).size.height - 300,
        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
        child: EasyRefresh(
            firstRefresh: true,
            firstRefreshWidget: PageFeedBack(firstRefresh: true).build(),
            emptyWidget: PageFeedBack(
              loading: loading,
              error: error,
              empty: _commentListModel.isEmpty,
              errorMsg: errorMsg,
              onErrorTap: () => _easyRefreshController.callRefresh(),
              onEmptyTap: () => _easyRefreshController.callRefresh(),
            ).build(),
            header: ClassicalHeader(),
            footer: ClassicalFooter(),
            controller: _easyRefreshController,
            enableControlFinishRefresh: false,
            enableControlFinishLoad: true,
            onRefresh: _onRefresh,
            onLoad: _commentListModel.isEmpty ? null : _onLoad,
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                      width: screenWidth(context),
                      margin: EdgeInsets.only(bottom: 15),
                      child: Text(
                        "共" +
                            widget.momentDetailData.commentCount.toString() +
                            "条评论",
                        style: TextStyle(fontSize: 13, color: Colors.grey[600]),
                      )),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: _commentListModel
                        .asMap()
                        .entries
                        .map((e) => InkWell(
                            onLongPress: () async {
                             Map<String, dynamic> localuserLogin = await SPUtil.getObject('userLogin');
                              if (localuserLogin['userId'] == e.value.userId) {
                                return showModalBottomSheet<int>(
                                    isScrollControlled: false,
                                    context: context,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: const BorderRadius.only(
                                        topLeft: Radius.circular(10),
                                        topRight: Radius.circular(10),
                                      ),
                                    ),
                                    builder: (BuildContext context) {
                                      return Container(
                                        constraints: BoxConstraints(
                                            minHeight: 60, maxHeight: 60),
                                        child: ListView.builder(
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            return ListTile(
                                                title: Text(options[index]),
                                                onTap: () async {
                                                  if (index == 0) {
                                                    await CommentService
                                                        .deleteComment({
                                                      "commentId": e.value.id
                                                    });
                                                    setState(() {
                                                      _commentListModel
                                                          .removeAt(e.key);
                                                    });
                                                  }
                                                  Navigator.of(context)
                                                      .pop(index);
                                                });
                                          },
                                          itemCount: options.length,
                                        ),
                                      );
                                    });
                              }
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                bottom: BorderSide(
                                    width: .5, color: WcaoTheme.outline),
                              )),
                              width: screenWidth(context),
                              margin: EdgeInsets.only(bottom: 15),
                              padding: EdgeInsets.only(bottom: 15),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(
                                    width: 30,
                                    height: 30,
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(15),
                                      child: CgqUtils.imageCache(
                                          e.value.userAvatarUrl,
                                          fit: BoxFit.cover),
                                    ),
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Expanded(
                                      child: InkWell(
                                          onTap: () {
                                            EventBusUtils.getInstance().fire(
                                                CommentEventPublish(e.value));
                                          },
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Text(
                                                e.value.userName,
                                                style: TextStyle(
                                                    color: Colors.black,
                                                    fontWeight: FontWeight.bold,
                                                    fontSize: 14),
                                              ),
                                              SizedBox(
                                                height: 3,
                                              ),

                                              Text(
                                                  getDateTime(
                                                      e.value.createTime),
                                                  style: TextStyle(
                                                      color: Colors.grey[400],
                                                      fontSize: 10)),

                                              SizedBox(
                                                height: 5,
                                              ),
                                              CommentParse(
                                                e.value.content,
                                                style: TextStyle(
                                                  fontSize: 12,
                                                  color: Colors.black,
                                                ),
                                              ),
                                              SizedBox(
                                                height: 5,
                                              ),
                                              // SizedBox(
                                              //   width: 5,
                                              // ),
                                              e.value.replyCount != null
                                                  ? InkWell(
                                                      child: Text(
                                                        e.value.replyCount
                                                                .toString() +
                                                            '回复',
                                                        style: TextStyle(
                                                            fontSize: 12,
                                                            fontWeight:
                                                                FontWeight.bold,
                                                            color: Colors
                                                                .blueAccent),
                                                      ),
                                                      onTap: () {
                                                        Get.to(CommentDetailPage(
                                                            momentId: widget
                                                                .momentDetailData
                                                                .id,
                                                            commentId:
                                                                e.value.id));
                                                      },
                                                    )
                                                  : Container(),
                                            ],
                                          ))),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Column(
                                    children: [
                                      LikeButton(
                                          isLiked: e.value.hasLiked,
                                          onTap: (isLiked) {
                                            return onTapLikeButton(
                                                !isLiked, e.key);
                                          },
                                          size: 20,
                                          circleColor: CircleColor(
                                              start: ColorRes.color_3,
                                              end: ColorRes.color_3),
                                          likeBuilder: (isLike) {
                                            return isLike == true
                                                ? Image.asset(
                                                    'assets/images/common/red_heart.webp')
                                                : Icon(
                                                    Icons
                                                        .favorite_border_outlined,
                                                    size: 20,
                                                    color: WcaoTheme.secondary,
                                                  );
                                          },
                                          bubblesColor: const BubblesColor(
                                            dotPrimaryColor: ColorRes.color_3,
                                            dotSecondaryColor: ColorRes.color_3,
                                            dotThirdColor: ColorRes.color_3,
                                            dotLastColor: ColorRes.color_3,
                                          )),
                                      Text(
                                        e.value.likeCount.toString(),
                                        style: TextStyle(
                                            fontSize: 12, color: Colors.grey),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            )))
                        .toList(),
                  ),
                ])));
  }

  Future<bool> onTapLikeButton(bool isLiked, int index) async {
    _commentListModel[index].hasLiked = isLiked;
    if (isLiked) {
      _commentListModel[index].likeCount++;
    } else {
      _commentListModel[index].likeCount--;
    }
    Map<String, dynamic> data = {
      "targetId": _commentListModel[index].id,
      "targetType": 'COMMENT',
    };
    if (isLiked) {
      await OperationServiece.like(data);
    } else {
      await OperationServiece.cancelLike(data);
    }
    setState(() {
      _commentListModel = _commentListModel;
    });
    return isLiked;
  }
}
